﻿Imports System.Data.Objects
Imports Telerik.Web.Mvc

<Authorize()>
Public Class AvisoController
    Inherits BaseController(Of Aviso)

    Private ReadOnly repoAviso_ As AvisoRepository
    Private ReadOnly repoPediatraAsindo_ As PediatraAsindoRepository
    Private ReadOnly repoPaciente_ As PacienteRepository
    Private ReadOnly repoTipoVía_ As TipoVíaRepository
    Private ReadOnly repoPoblación_ As PoblaciónRepository
    Private ReadOnly repoDirección_ As DirecciónRepository

    Public Sub New(ByVal repoPediatraAsindo As PediatraAsindoRepository, ByVal saver As ContextSaver,
        ByVal repoAviso As AvisoRepository,
        ByVal repoPacientes As PacienteRepository,
        ByVal repoTipoVía As TipoVíaRepository,
        ByVal repoPoblación As PoblaciónRepository,
        ByVal repoDirección As DirecciónRepository)
        MyBase.New(repoPediatraAsindo, saver)
        repoAviso_ = repoAviso
        repoPediatraAsindo_ = repoPediatraAsindo
        repoPaciente_ = repoPacientes
        repoTipoVía_ = repoTipoVía
        repoPoblación_ = repoPoblación
        repoDirección_ = repoDirección
    End Sub

#Region " Lista "

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks>
    ''' GET: /Aviso
    ''' </remarks>
    Function Lista() As ViewResult
        Return ListaGrid(New GridCommand, Nothing, Nothing)
    End Function

    Function ListaPaciente(paciente As Integer) As ViewResult
        Return ListaGrid(New GridCommand, paciente, Nothing)
    End Function

    Function ListaPediatra(pediatra As Integer) As ViewResult
        Return ListaGrid(New GridCommand, Nothing, pediatra)
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks>
    ''' GET: /Aviso
    ''' </remarks>
    <GridAction(GridName:="Grid", EnableCustomBinding:=True)> _
    Function ListaGrid(command As GridCommand, paciente As Integer?, pediatra As Integer?) As ViewResult
        Dim data = GetServerData(command, paciente, pediatra)
        Dim titulo = "Avisos"
        If paciente.HasValue Then
            Dim pacienteBD = repoPaciente_.GetByID(paciente.Value)
            titulo = titulo & " del paciente " & pacienteBD.NombreCompletoDerecho
        End If
        If pediatra.HasValue Then
            Dim pediatraBD = repoPediatraAsindo_.GetByID(pediatra.Value)
            titulo = titulo & " atendidos por " & pediatraBD.NombreCompletoDerecho
        End If
        Return Mostrar(data, titulo)
    End Function

    Private Function GetServerData(command As GridCommand, paciente As Integer?, pediatra As Integer?) As IEnumerable(Of Aviso)
        Dim data = repoAviso_.All.Include("Paciente").Include("Dirección.Población").Include("Dirección.TipoVía").Include("PediatraAsindo")
        'Apply filtering (use command.FilterDescriptors)
        data = data.ApplyFiltering(command.FilterDescriptors)
        If paciente.HasValue Then
            data = data.Where(Function(avis) avis.PacienteId = paciente.Value)
        End If
        If pediatra.HasValue Then
            data = data.Where(Function(avis) avis.PediatraAsindoId = pediatra.Value)
        End If
        ViewData("Total") = data.Count()

        'Apply sorting (use command.GroupDescriptors, command.SortDescriptors)
        data = data.ApplySorting(command.GroupDescriptors, command.SortDescriptors)
        'Apply paging (use command.Page, command.PageSize)
        data = data.ApplyPaging(command.Page, command.PageSize)
        'Apply grouping
        'If command.GroupDescriptors.Any() Then
        '    Return data.ApplyGrouping(command.GroupDescriptors)
        'End If
        Return data.ToArray
    End Function

    Private Function IsEmptyCommand(command As GridCommand) As Boolean
        Return command.PageSize = 0
    End Function


#End Region

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks>
    ''' GET: /Aviso/Crear
    ''' </remarks>
    Function Crear() As ViewResult
        Return Mostrar(repoAviso_.CreateDetached, "Nuevo aviso")
    End Function

    '
    ' POST: /Aviso/Crear

    <HttpPost()> _
    Function Crear(ByVal aviso As Aviso, <Bind(Prefix:="midir")> ByVal direcForm As Dirección) As ActionResult
        Try
            Dim dirVal As New DirecciónValidator

            Dim valResults = dirVal.Validate(direcForm)

            If Not valResults.IsValid Then
                For Each fail In valResults.Errors
                    ModelState.AddModelError("midir." & fail.PropertyName, fail.ErrorMessage)
                Next
                Return Mostrar(aviso, "Nuevo aviso")
            End If
            repoAviso_.Add(aviso, save:=False)
            aviso.Dirección = repoDirección_.AddIfNotExists(direcForm)
            Saver.Save()
            aviso = repoAviso_.GetByID(aviso.Id, "Paciente")
            TempData("info") = String.Format("Aviso del {0:dd/MM/yyyy} para {1} creado correctamente", aviso.Fecha, aviso.Paciente.NombreCompleto)
            Return RedirectToAction("Lista")
        Catch ex As Exception
            Return Mostrar(repoAviso_.CreateDetached, "Nuevo aviso", "Error al crear aviso: " & ex.Message)
        End Try
    End Function

    '
    ' GET: /Aviso/Editar/5

    Function Editar(ByVal id As Integer) As ViewResult
        Dim aviso = repoAviso_.GetByID(id, "Dirección")
        Return Mostrar(aviso, aviso.Completo)
    End Function


    <HttpPost()> _
    Function Editar(ByVal id As Integer, <Bind(Prefix:="midir")> ByVal direcForm As Dirección) As ActionResult
        Dim aviso = repoAviso_.GetByID(id, "Paciente")
        Try
            UpdateModel(aviso)

            aviso.Dirección = repoDirección_.AddIfNotExists(direcForm)
            repoDirección_.BorrarHuérfanas()
            Saver.Save()

            TempData("info") = String.Format("{0} modificado correctamente", aviso.Completo)
            Return RedirectToAction("Lista")
        Catch ex As Exception
            Return Mostrar(aviso, aviso.Completo, "Error al editar aviso: " & ex.Message)
        End Try
    End Function

    '
    ' POST: /Aviso/Borrar/5

    <HttpPost()>
    Function Borrar(ByVal id As Integer) As ActionResult
        Dim aviso = repoAviso_.GetByID(id, "Paciente")
        Try
            Dim paciente = aviso.Paciente
            repoAviso_.Delete(aviso, save:=False)
            repoDirección_.BorrarHuérfanas()
            Saver.Save()
            TempData("info") = String.Format("Aviso del {0:dd/MM/yyyy} para {1} borrado correctamente", aviso.Fecha, paciente.NombreCompleto)
            Return RedirectToAction("Lista")
        Catch ex As Exception
            Return Mostrar(aviso, aviso.Completo, "Error al borrar aviso: " & ex.Message & If(ex.InnerException Is Nothing, "", "; " & ex.InnerException.Message))
        End Try
    End Function

    Protected Overrides Sub CargarDatosComunes()
        ViewData("ListaPediatrasAsindo") = repoPediatraAsindo_.Desplegable
        ViewData("ListaPacientes") = repoPaciente_.Desplegable
        ViewData("ListaPoblaciones") = repoPoblación_.Desplegable
        ViewData("ListaTiposVia") = repoTipoVía_.Desplegable
    End Sub


    Protected Overrides Function VistaFormulario() As String
        Return "FormAviso"
    End Function

    Protected Overrides Function VistaLista() As String
        Return "ListaAvisos"
    End Function

End Class
